package com.gexiaobao.pigeon.app.util

import android.content.Context
import android.content.res.ColorStateList
import android.graphics.Color
import android.graphics.PorterDuff
import android.location.Location
import android.os.Build
import android.preference.PreferenceManager
import android.text.TextUtils
import android.widget.ProgressBar
import androidx.appcompat.widget.AppCompatTextView
import androidx.core.content.ContextCompat
import com.blankj.utilcode.util.Utils
import com.gexiaobao.pigeon.R
import com.gexiaobao.pigeon.app.ext.RxTextTool
import com.gexiaobao.pigeon.app.ext.loadcallback.LoadingCallback
import com.kingja.loadsir.core.LoadService
import com.tencent.mmkv.MMKV
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.MultipartBody
import okhttp3.RequestBody
import okhttp3.RequestBody.Companion.asRequestBody
import java.io.File
import java.math.BigDecimal
import kotlin.math.abs


object SettingUtil {

    fun getTextFormat(context: Context, id: Int): String {
        return context.resources.getString(id)
    }

    fun filesToMultipartBody(files: HashMap<String, File?>, params: HashMap<String, String>): MultipartBody {
        val builder = MultipartBody.Builder()
        for (key in files.keys) {
            val requestBody: RequestBody? = files[key]?.asRequestBody("image/*".toMediaTypeOrNull())
            requestBody?.let { builder.addFormDataPart(key, files[key]?.name, it) }
        }
        for (key in params.keys) {
            params[key]?.let { builder.addFormDataPart(key, it) }
        }
        builder.setType(MultipartBody.FORM)
        return builder.build()
    }

    fun fileListToMultipartBody(files: HashMap<String, ArrayList<File>>, params: HashMap<String, String>): MultipartBody {
        val builder = MultipartBody.Builder()

        for ((key, fileImage) in files.entries) {
            for (i in 0 until fileImage.size) {
                val requestBody: RequestBody = fileImage[i].asRequestBody("image/*".toMediaTypeOrNull())
                requestBody.let { builder.addFormDataPart(key, fileImage[i].name, it) }
            }
        }

        for (key in params.keys) {
            params[key]?.let { builder.addFormDataPart(key, it) }
        }
        builder.setType(MultipartBody.FORM)
        return builder.build()
    }

    fun fileImageListToMultipartBody(files: HashMap<String, ArrayList<File>>): MultipartBody {
        val builder = MultipartBody.Builder()
        for ((key, fileImage) in files.entries) {
            for (i in 0 until fileImage.size) {
                val requestBody: RequestBody = fileImage[i].asRequestBody("image/*".toMediaTypeOrNull())
                requestBody.let { builder.addFormDataPart(key, fileImage[i].name, it) }
            }
        }
        builder.setType(MultipartBody.FORM)
        return builder.build()
    }

    /**
     * 获取当前主题颜色
     */
    fun getColor(context: Context): Int {
        val setting = PreferenceManager.getDefaultSharedPreferences(context)
        val defaultColor = ContextCompat.getColor(context, R.color.colorPrimary)
        val color = setting.getInt("color", defaultColor)
        return if (color != 0 && Color.alpha(color) != 255) {
            defaultColor
        } else {
            color
        }
    }

    /**
     * 设置主题颜色
     */
    fun setColor(context: Context, color: Int) {
        val setting = PreferenceManager.getDefaultSharedPreferences(context)
        setting.edit().putInt("color", color).apply()
    }

    /**
     * 获取列表动画模式
     */
    fun getListMode(): Int {
        val kv = MMKV.mmkvWithID("app")
        //0 关闭动画 1.渐显 2.缩放 3.从下到上 4.从左到右 5.从右到左
        return kv.decodeInt("mode", 2)
    }

    fun getOneColorStateList(context: Context): ColorStateList {
        val colors = intArrayOf(getColor(context))
        val states = arrayOfNulls<IntArray>(1)
        states[0] = intArrayOf()
        return ColorStateList(states, colors)
    }

    fun getOneColorStateList(color: Int): ColorStateList {
        val colors = intArrayOf(color)
        val states = arrayOfNulls<IntArray>(1)
        states[0] = intArrayOf()
        return ColorStateList(states, colors)
    }

    /**
     * 设置loading的颜色 加载布局
     */
    fun setLoadingColor(color: Int, loadsir: LoadService<Any>) {
        loadsir.setCallBack(LoadingCallback::class.java) { _, view ->
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                view.findViewById<ProgressBar>(R.id.loading_progress).indeterminateTintMode = PorterDuff.Mode.SRC_ATOP
                view.findViewById<ProgressBar>(R.id.loading_progress).indeterminateTintList = getOneColorStateList(color)
            }
        }
    }

    /**
     * 转换纬度格式
     */
    fun convertToLat(latitude: Double): String {
        val builder = StringBuilder()
        val latitudeDegrees = Location.convert(abs(latitude), Location.FORMAT_SECONDS)
        val latitudeSplit = latitudeDegrees.split(":".toRegex()).toTypedArray()
        builder.append(latitudeSplit[0])
        builder.append("°")
        builder.append(latitudeSplit[1])
        builder.append("′")
        builder.append(latitudeSplit[2])
        builder.append("″")
        return builder.toString().trim()
    }

    /**
     * 转换经度格式
     */
    fun convertToLon(longitude: Double): String {
        val builder = StringBuilder()
        val longitudeDegrees = Location.convert(abs(longitude), Location.FORMAT_SECONDS)
        val longitudeSplit = longitudeDegrees.split(":".toRegex()).toTypedArray()
        builder.append(longitudeSplit[0])
        builder.append("°")
        builder.append(longitudeSplit[1])
        builder.append("′")
        builder.append(longitudeSplit[2])
        builder.append("″")
        return builder.toString().trim()
    }

    /**
     * 以字符串形式输入经纬度的转换
     * 度分秒转化为小数点格式
     * @params:latlng 116°25'7.85"
     */
    fun convertToDecimalByString(latlng: String): Double {
        val du = latlng.substring(0, latlng.indexOf("°")).toDouble()
        val fen = latlng.substring(latlng.indexOf("°") + 1, latlng.indexOf("′")).toDouble()
        val miao = latlng.substring(latlng.indexOf("′") + 1, latlng.indexOf("″")).toDouble()
        var result = 0.0
        result = if (du < 0) {
            (Math.abs(du) + fen / 60 + miao / 60 / 60)
        } else {
            du + fen / 60 + miao / 60 / 60
        }
        return result
    }

    fun getColorStateList(color: Int): ColorStateList {
        val colors = intArrayOf(color, ContextCompat.getColor(Utils.getApp(), R.color.colorGray))
        val states = arrayOfNulls<IntArray>(2)
        states[0] = intArrayOf(android.R.attr.state_checked, android.R.attr.state_checked)
        states[1] = intArrayOf()
        return ColorStateList(states, colors)
    }

    fun getColorStateList(context: Context): ColorStateList {
        val colors = intArrayOf(getColor(context), ContextCompat.getColor(context, R.color.colorGray))
        val states = arrayOfNulls<IntArray>(2)
        states[0] = intArrayOf(android.R.attr.state_checked, android.R.attr.state_checked)
        states[1] = intArrayOf()
        return ColorStateList(states, colors)
    }

    /**
     * 提供（相对）精确的除法运算。当发生除不尽的情况时，由scale参数指
     * 定精度，以后的数字四舍五入。
     * @param v1 被除数
     * @param v2 除数
     * @param scale 表示表示需要精确到小数点以后几位。
     * @return 两个参数的商
     */
    fun div(v1: Double, v2: Double, scale: Int): Double {
        if (scale < 0) {
            throw IllegalArgumentException(
                "The scale must be a positive integer or zero"
            )
        }
        val b1 = BigDecimal(v1)
        val b2 = BigDecimal(v2)
        return b1.divide(b2, scale, BigDecimal.ROUND_HALF_UP).toDouble()
    }

    fun cns(msg: String?): String {
        return checkNullString(msg)
    }

    fun checkNullString(msg: String?): String {
        if (msg == null) {
            return ""
        }
        return if (TextUtils.isEmpty(msg) || "null" == msg) {
            ""
        } else {
            msg
        }
    }

    fun pickOrderStatus(type: Int): String? {
        return try {
            Dict.shopOrderStatus[type]
        } catch (e: Exception) {
            ""
        }
    }

    /** 物流类型 */
    fun deliveryType(type: String): String {
        return try {
            Dict.deliveryType[type].toString()
        } catch (e: Exception) {
            ""
        }
    }

    /**
     * 根据订单状态设置文字颜色
     */
    fun pickOrderStatusColor(type: Int): Int? {
        return try {
            Dict.shopOrderStatusColor[type]
        } catch (e: Exception) {
            0
        }
    }

    fun pickBigOrderBusinessType(type: Int?): String? {
        return try {
            Dict.orderBigBusinessTypeHaspMap[type]
        } catch (e: Exception) {
            ""
        }
    }

    fun pickBigOrderBusinessState(status: Int?): String? {
        return try {
            Dict.orderBigBusinessStateHaspMap[status]
        } catch (e: Exception) {
            ""
        }
    }

    fun pickPigeonSexState(status: Int?): String? {
        return try {
            Dict.pigeonSexHaspMap[status]
        } catch (e: Exception) {
            ""
        }
    }

    fun setPrice(price: String, tvPrice: AppCompatTextView, tvSize: Int, textColor: Int) {
        if (price.isNotEmpty() && price.contains(".")) {
            val integerY = price.split(".")
            if (integerY.isNotEmpty()) {
                RxTextTool.getBuilder("")
                    .append("¥")
                    .append(integerY[0]).setBold().setAppearance(tvSize).setTextColor(textColor)
                    .append(".")
                    .append(integerY[1])
                    .into(tvPrice)
            }
        } else {
            tvPrice.text = "¥0.0"
        }
    }
}
